package com.example.villagemarket;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.Provider.Service;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.json.JSONException;
import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;


public class PostCheckout extends Activity {

	private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_NO_NETWORK;

	// Used to save the context to use as a toast in the Asynch task
	Context c;
	
	EditText email_delivery;
	EditText email_pickup;
	EditText name;
	EditText address;
	EditText city;
	EditText state;
	EditText zip;

	// note that these credentials will differ between live & sandbox
	// environments.
	private static final String CONFIG_CLIENT_ID = "AaMI6xBMQoY5HruzNSsIk7X_-RopXjKufVooPl4pcbWEMf7ABZgCFGqHWPfk";

	private static final int REQUEST_CODE_PAYMENT = 1;
	private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;

	RadioButton pickup;
	RadioButton delivery;

	private static PayPalConfiguration config = new PayPalConfiguration()
			.environment(CONFIG_ENVIRONMENT)
			.clientId(CONFIG_CLIENT_ID)
			// The following are only used in PayPalFuturePaymentActivity.
			.merchantName("Village Market")
			.merchantPrivacyPolicyUri(
					Uri.parse("https://www.example.com/privacy"))
			.merchantUserAgreementUri(
					Uri.parse("https://www.example.com/legal"));

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_post_checkout);

		c = this;

		Intent intent = new Intent(this, PayPalService.class);
		intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
		startService(intent);

		pickup = (RadioButton) findViewById(R.id.button_pickup);
		delivery = (RadioButton) findViewById(R.id.button_delivery);
		
		email_delivery = (EditText) findViewById(R.id.email_delivery);
		email_pickup = (EditText) findViewById(R.id.email_pickup);
		name = (EditText) findViewById(R.id.name_delivery);
		address  = (EditText) findViewById(R.id.address_delivery);
		city = (EditText) findViewById(R.id.city_delivery);
		state = (EditText) findViewById(R.id.state_delivery);
		zip = (EditText) findViewById(R.id.zip_delivery);
		

		pickup.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				email_pickup.setVisibility(View.VISIBLE);
				email_delivery.setVisibility(View.INVISIBLE);
				name.setVisibility(View.INVISIBLE);
				address.setVisibility(View.INVISIBLE);
				city.setVisibility(View.INVISIBLE);
				state.setVisibility(View.INVISIBLE);
				zip.setVisibility(View.INVISIBLE);
				
				
				


			}

		});

		delivery.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {



				name.setVisibility(View.VISIBLE);
				address.setVisibility(View.VISIBLE);
				city.setVisibility(View.VISIBLE);
				state.setVisibility(View.VISIBLE);
				zip.setVisibility(View.VISIBLE);
				email_pickup.setVisibility(View.INVISIBLE);
				email_delivery.setVisibility(View.VISIBLE);
				email_delivery.requestFocus();

				

			}

		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.post_checkout, menu);
		return true;
	}
	
	public void cancelButton(View v)
	{
		Intent i = new Intent(getApplicationContext(), ViewShoppingCart.class);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void checkout(View v) {

		RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
		int id = radioGroup.getCheckedRadioButtonId();
		
		Customer c = new Customer();
		
		if (id == R.id.button_pickup) {
			if (email_pickup.getText().toString().equals("")) {
				Toast.makeText(this,
						"Please make sure all fields are filled in!",
						Toast.LENGTH_SHORT).show();
			} else {
				
				c.setEmail(email_pickup.getText().toString());
				c.setShippingOption("pickup");
				
				BigDecimal total = ShoppingCart.getTotal();
				PayPalPayment thingToBuy = new PayPalPayment(total, "USD",
						c.getEmail(), PayPalPayment.PAYMENT_INTENT_SALE);

				Intent intent = new Intent(this, PaymentActivity.class);

				intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

				startActivityForResult(intent, REQUEST_CODE_PAYMENT);

				
			}
		} else if (id == R.id.button_delivery) {
			if (name.getText().toString().equals("")
					|| address.getText().toString().equals("")
					|| city.getText().toString().equals("")
					|| state.getText().toString().equals("")
					|| zip.getText().toString().equals("")
					|| email_delivery.getText().toString().equals("")) {
				Toast.makeText(this,
						"Please make sure all fields are filled in!",
						Toast.LENGTH_SHORT).show();
			} else {

				c.setName(name.getText().toString());
				c.setAddress(address.getText().toString());
				c.setCity(city.getText().toString());
				c.setState(state.getText().toString());
				c.setZip(zip.getText().toString());
				c.setEmail(email_delivery.getText().toString());
				c.setShippingOption("delivery");
				
				BigDecimal total = ShoppingCart.getTotal();
				PayPalPayment thingToBuy = new PayPalPayment(total, "USD",
						c.getEmail(), PayPalPayment.PAYMENT_INTENT_SALE);

				Intent intent = new Intent(this, PaymentActivity.class);

				intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

				startActivityForResult(intent, REQUEST_CODE_PAYMENT);

			}
		}
		


	}

	public void onFuturePaymentPressed(View pressed) {
		Intent intent = new Intent(PostCheckout.this,
				PayPalFuturePaymentActivity.class);

		startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_PAYMENT) {
			if (resultCode == Activity.RESULT_OK) {
				PaymentConfirmation confirm = data
						.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
				if (confirm != null) {
					try {
						Log.i("paymentExample", confirm.toJSONObject()
								.toString(4));

						// TODO: send 'confirm' to your server for verification
						// or consent
						// completion.
						// see
						// https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
						// for more details.

						Session session = createSessionObject();

						String itemsAndPricesInCart = retrieveItemsAndPrices();
						try {
							Message message = createMessage(
									Customer.getEmail(), "Order confirmation",
									itemsAndPricesInCart, session);
							new SendMailTask().execute(message);
						} catch (AddressException e) {
							e.printStackTrace();
						} catch (MessagingException e) {
							e.printStackTrace();
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}

						Toast.makeText(
								getApplicationContext(),
								"PaymentConfirmation info received from PayPal",
								Toast.LENGTH_LONG).show();

					} catch (JSONException e) {
						Log.e("paymentExample",
								"an extremely unlikely failure occurred: ", e);
					}
				}
			} else if (resultCode == Activity.RESULT_CANCELED) {
				Log.i("paymentExample", "The user canceled.");
			} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
				Log.i("paymentExample",
						"An invalid Payment was submitted. Please see the docs.");
			}
		} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
			if (resultCode == Activity.RESULT_OK) {
				PayPalAuthorization auth = data
						.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
				if (auth != null) {
					try {
						Log.i("FuturePaymentExample", auth.toJSONObject()
								.toString(4));

						String authorization_code = auth.getAuthorizationCode();
						Log.i("FuturePaymentExample", authorization_code);

						sendAuthorizationToServer(auth);
						Toast.makeText(getApplicationContext(),
								"Future Payment code received from PayPal",
								Toast.LENGTH_LONG).show();

					} catch (JSONException e) {
						Log.e("FuturePaymentExample",
								"an extremely unlikely failure occurred: ", e);
					}
				}
			} else if (resultCode == Activity.RESULT_CANCELED) {
				Log.i("FuturePaymentExample", "The user canceled.");
			} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
				Log.i("FuturePaymentExample",
						"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
			}
		}
	}

	private String retrieveItemsAndPrices() {
		StringBuilder sb = new StringBuilder();
		sb.append("Hello,\n\n");
		sb.append("This is a receipt for your recent purchase at The Village Market\n\n");

		for (Map.Entry<String, ArrayList<String>> entry : ShoppingCart.items
				.entrySet()) {
			ArrayList<String> value = entry.getValue();
			// Amount
			sb.append(value.get(0) + " of ");

			String description = entry.getKey();
			sb.append(description + " at ");

			sb.append(value.get(1) + "\n");

		}

		sb.append("\n for a grand total of "
				+ ShoppingCart.getTotal().toString() + "\n\n");

		if (Customer.getShippingOption().equals("delivery")) {
			sb.append("You have chosen to have this order delivered to your address.\n");
			sb.append("This order will be shipped to: \n");
			sb.append(Customer.getAddress() + "\n");
			sb.append(Customer.getCity() + ", " + Customer.getState() + " "
					+ Customer.getZip() + "\n\n");
		} else {
			sb.append("You have chosen to pick up this order in the store.\n");
			sb.append("The address to the Village Market is: \n");
			sb.append("806 S Main Street \n");
			sb.append("Fond du Lac, WI 54935\n");
			sb.append("If you have any questions, please call us at 920-922-2265\n\n");
		}

		sb.append("Thank you for your business!");

		return sb.toString();
	}

	private void sendAuthorizationToServer(PayPalAuthorization authorization) {

		// TODO:
		// Send the authorization response to your server, where it can exchange
		// the authorization code
		// for OAuth access and refresh tokens.
		//
		// Your server must then store these tokens, so that your server code
		// can execute payments
		// for this user in the future.

	}

	public void onFuturePaymentPurchasePressed(View pressed) {
		// Get the Application Correlation ID from the SDK
		String correlationId = PayPalConfiguration
				.getApplicationCorrelationId(this);

		Log.i("FuturePaymentExample", "Application Correlation ID: "
				+ correlationId);

		// TODO: Send correlationId and transaction details to your server for
		// processing with
		// PayPal...
		Toast.makeText(getApplicationContext(),
				"App Correlation ID received from SDK", Toast.LENGTH_LONG)
				.show();
	}

	@Override
	public void onDestroy() {
		// Stop service when done
		stopService(new Intent(this, PayPalService.class));
		super.onDestroy();
	}

	private Session createSessionObject() {
		Properties properties = new Properties();
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.port", "587");

		return Session.getInstance(properties, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("vm.android.app@gmail.com",
						"Probiotic1");
			}
		});
	}

	private Message createMessage(String email, String subject,
			String messageBody, Session session) throws MessagingException,
			UnsupportedEncodingException {
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress("vm.android.app@gmail.com",
				"Do-Not-Reply"));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(
				email, email));
		message.setSubject(subject);
		message.setText(messageBody);
		return message;
	}

	private class SendMailTask extends AsyncTask<Message, Void, Void> {
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(c, "Please wait",
					"Sending email to " + Customer.getEmail(), true, false);
		}

		@Override
		protected void onPostExecute(Void aVoid) {
			super.onPostExecute(aVoid);
			progressDialog.dismiss();
		}

		@Override
		protected Void doInBackground(Message... messages) {
			try {
				Transport.send(messages[0]);
			} catch (MessagingException e) {
				e.printStackTrace();
			}
			return null;
		}
	}

}
